package xxhui.space.newsclient.Fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import xxhui.space.newsclient.Adapter.HeadLineRecyclerViewAdapter;
import xxhui.space.newsclient.Bean.HeadlineItem;
import xxhui.space.newsclient.Bean.News;
import xxhui.space.newsclient.Http.NewsLoader;
import xxhui.space.newsclient.R;
import xxhui.space.newsclient.UserDetailActivity;

import static android.content.ContentValues.TAG;


/**
 * A simple {@link Fragment} subclass.
 */
public class ArticleFragment extends Fragment implements HeadLineRecyclerViewAdapter.OnItemClickListener {

    @BindView(R.id.rc_list)
    RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private HeadLineRecyclerViewAdapter adapter;
    private Handler handler;
    @BindView(R.id.headlines_title)
    TextView tv_title;
    private Unbinder unbinder;
    private NewsLoader loader = new NewsLoader();

    public ArticleFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        handler = new Handler();
        View view = inflater.inflate(R.layout.fragment_article, container, false);
        unbinder = ButterKnife.bind(this, view);
        layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        //设置标题高度
        tv_title.getLayoutParams().height = tv_title.getLayoutParams().height*3/4;

        loadRecyclerViewData();
        //加载RecycleView的数据
        adapter = new HeadLineRecyclerViewAdapter(null,getContext());
        adapter.setOnItemClickListener(this);
        recyclerView.setAdapter(adapter);
        return view;
    }

    public List<HeadlineItem> getData(){
        List<HeadlineItem> list = new ArrayList<HeadlineItem>();
        for(int i=0 ; i<15 ;i++){
            list.add(new HeadlineItem("","用户名","仅仅7天，3万把共享雨伞全军覆没！不盈利真当做公益了？",
                    "全国暴雨季如期而至，街上的同享单车全都惨兮兮地淋在雨里，骑行人次显着削减。但这让人想起别的一个刚刚鼓起不久的项目——同享雨伞。风口等了这么久，总算轮到它上场了。123456789",""));
        }
        return list;
    }

    public void loadRecyclerViewData(){
        loader.getArticle(1,10).subscribe(new Observer<News>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                Log.i(TAG, "onSubscribe: ");
            }

            @Override
            public void onNext(@NonNull News news) {
                Log.i(TAG, "onNext: "+news);
                if(news==null&&news.getData().size()==0){
                    return;
                }
                List<HeadlineItem> list = news.conversionData();
                //加载RecycleView的数据
                adapter.setData(list);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });
            }

            @Override
            public void onError(@NonNull Throwable e) {
                Log.i(TAG, "onError: ");
                Toast.makeText(getContext(), "网络出现了点小差错，请重试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete() {
                Log.i(TAG, "onComplete: ");
            }
        });
    }

//    public void loadRecyclerViewData(){
//        OkHttpClient okHttpClient = MyApplication.okHttpClient;
//        if(okHttpClient==null){
//            return;
//        }
//        StringBuilder builder = new StringBuilder();
//        builder.append("http://interview.jbangit.com/news");
//        String loginUrl = builder.toString();
//        System.out.println(loginUrl);
//        Request request = new Request.Builder().url(loginUrl).build();
//        OkHttpCallback callback = new  OkHttpCallback() {
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String result = response.body().string();
//                System.out.println("success!");
//                News news = new Gson().fromJson(result, new TypeToken<News>() {
//                }.getType());
//                if(news==null&&news.getData().size()==0){
//                    return;
//                }
//                List<HeadlineItem> list = news.conversionData();
//                //加载RecycleView的数据
//                adapter.setData(list);
//                handler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        adapter.notifyDataSetChanged();
//                    }
//                });
//            }
//
//            @Override
//            public void onFailure(Call call, IOException e) {
//                System.out.println("error is happen");
//            }
//        };
//        okHttpClient.newCall(request).enqueue(callback);
//    }

    @Override
    public void onItemClick(View v, int position) {
        startActivity(new Intent(getContext(), UserDetailActivity.class));

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
